<template>
	<view :class="currentTheme">
		<a-nabbar :is-back="false" name="聊天" />
		<view class="u-padding-32 content">
			<view v-for="(item, index) in dataList" :key="item.id" class="u-margin-bottom-10">
				<u-swipe-action
					:show="item.show"
					bg-color="#1f1b34"
					@content-click="goPath"
					btn-width="240"
					@click="click"
					@open="open"
					:index="index"
					:options="item.isTop ? unOption : options"
				>
					<item-box padding="20">
						<view class="item u-flex u-position-relative">
							<view class="u-position-relative">
								<!-- <u-badge  bgColor='#694EF6' :count="item.unReadCount || 0" :offset="[0,0]"> -->
								<u-badge bgColor="#ff0101" :count="item.unReadCount || 0" :offset="[0, 0]"></u-badge>
								<item-image :type="'1'" :img="item.avatar" :size="100" />
							</view>
							<view class="title-wrap u-margin-left-20 u-flex-1" style="flex-shrink: 0;">
								<view class=" u-font-36 text-last-msg content-desc-item">{{ item.chatName || '' }}</view>
								<view class="u-font-26 text-last-msg u-margin-top-16 text-order-666">{{ item.data || '' }}</view>
								<view class="time u-position-absolute text-order-666 u-font-24">{{ item.dateTimeNum | filterTime }}</view>
							</view>
						</view>
					</item-box>
				</u-swipe-action>
			</view>
		</view>
		<empty v-if="dataList.length === 0"></empty>
	</view>
</template>

<script>
import empty from '@/components/mescroll-uni/components/mescroll-empty.vue';
const WebIM = require('@/utils/WebIM')['default'];
const disp = require('@/utils/broadcast');
import dayjs from 'dayjs';
import { formatTime } from '@/utils/index.js';
import { add } from '@/api/crud.js';
let msgStorage = require('@/components/chat/msgstorage');
export default {
	components: {
		empty
	},
	data() {
		return {
			dataList: [],
			labelStyle: {
				fontSize: '24rpx'
			},
			listGroup: [],
			__visibility__: false,
			options: [
				{
					text: '置顶',
					style: {
						backgroundColor: '#765cfe'
					}
				},
				{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}
			],
			unOption: [
				{
					text: '取消置顶',
					style: {
						backgroundColor: '#765cfe'
					}
				},
				{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}
			]
		};
	},
	onShow() {
		this.__visibility__ = true;
		if (!this.$store.getters.loginForm.uid) return false;
		this.getList();
	},
	onLoad() {
		const me = this;
		if (!this.$store.getters.loginForm.uid) return false;
		//监听解散群
		disp.on('em.invite.deleteGroup', () => {
			this.getList();
		});
		msgStorage.on('newChatMsg', _ => {
			if (this.__visibility__) this.getList();
		});
		//监听未读消息数
		disp.on('em.unreadspot', () => {
			me.getList();
		});
	},
	methods: {
		//点击置顶或者删除按钮
		click(index, index1) {
			setTimeout(() => {
				this.dataList = this.dataList.map((val, idx) => {
					this.$set(val, 'show', false);
					return val;
				});
			}, 100);
			const item = this.dataList[index];
			const key = `${item.username}${this.$store.getters.loginForm.hxUsername}`;
			const historyChatMsgKeys = `rendered_${key}`;
			let historyChatMsgs = uni.getStorageSync(historyChatMsgKeys);
			let newChatMsgs = uni.getStorageSync(key);
			if (index1 == 1) {
				//删除
				uni.removeStorageSync(historyChatMsgKeys);
				uni.removeStorageSync(key);
				this.dataList.splice(index, 1);
			} else {
				//置顶
				this.setTopMsg(key, historyChatMsgKeys, historyChatMsgs, newChatMsgs, index);
			}
		},
		//置顶方法
		setTopMsg(key, historyChatMsgKeys, historyChatMsgs, newChatMsgs, index) {
			this.dataList[index].isTop = !this.dataList[index].isTop;
			const item = this.dataList[index];
			if (newChatMsgs && newChatMsgs.length > 0) {
				newChatMsgs = newChatMsgs.map(val => {
					val.isTop = item.isTop;
					return val;
				});
				uni.setStorageSync(key, newChatMsgs);
			}
			if (historyChatMsgs && historyChatMsgs.length > 0) {
				historyChatMsgs = historyChatMsgs.map(val => {
					val.isTop = item.isTop;
					return val;
				});
				uni.setStorageSync(historyChatMsgKeys, historyChatMsgs);
			}
			this.dataList.sort(a => (a.isTop ? -1 : 1));
		},
		// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
		open(index) {
			// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
			// 原本为'false'，再次设置为'false'会无效
			this.dataList[index].show = true;
			this.dataList.map((val, idx) => {
				if (index != idx) this.dataList[idx].show = false;
			});
		},
		// 包含陌生人版本
		async getList() {
			await WebIM.conn.getGroup({
				success: res => (this.listGroup = res.data)
			});
			const ids = this.listGroup.map(val => val.groupid);
			await add(
				{
					singleData: ids,
					showLoading: true,
					type: 'single' //不是对象
				},
				'chatGroup',
				'shopApi',
				'queryByChatGroupIds'
			).then(res => {
				res.forEach(val => {
					const item = this.listGroup.find(c => c.groupid == val.hxChatGroupId);
					if (item) {
						this.$set(item, 'chatName', val.nickname);
						this.$set(item, 'avatar', val.avatar);
					}
				});
			});
			var myName = uni.getStorageSync('myUsername');
			var array = [];
			const me = this;
			uni.getStorageInfo({
				success: res => {
					let storageKeys = res.keys;
					let newChatMsgKeys = [];
					let historyChatMsgKeys = [];
					storageKeys.forEach(item => {
						const isMe = item.indexOf(myName) > -1;
						const rendered = item.indexOf('rendered_');
						if (isMe && rendered == -1) newChatMsgKeys.push(item);
						if (isMe && rendered > -1) historyChatMsgKeys.push(item);
					});
					this.cul(newChatMsgKeys, historyChatMsgKeys);
				}
			});
		},
		returnChatMsg(chatMsgs) {
			console.log(chatMsgs);
			if (!Array.isArray(chatMsgs)) return {};
			const lastChatMsg = chatMsgs[chatMsgs.length - 1];
			lastChatMsg.dateTimeNum = dayjs(lastChatMsg.time).valueOf();
			return lastChatMsg;
		},
		cul(newChatMsgKeys, historyChatMsgKeys) {
			let array = [];
			let lastChatMsg;
			historyChatMsgKeys.forEach(val => {
				let index = newChatMsgKeys.indexOf(val.slice(9));
				let newChatMsgs = uni.getStorageSync(newChatMsgKeys[index]) || [];
				if (index > -1 && newChatMsgs.length) {
					lastChatMsg = this.returnChatMsg(newChatMsgs);
					lastChatMsg.unReadCount = this.unReadCount(newChatMsgs);
					newChatMsgKeys.splice(index, 1);
				} else {
					let historyChatMsgs = uni.getStorageSync(val);
					if (historyChatMsgs.length) {
						lastChatMsg = this.returnChatMsg(historyChatMsgs);
						//lastChatMsg.dateTimeNum = dayjs(lastChatMsg.time).valueOf()
					}
				}
				lastChatMsg && array.push(lastChatMsg);
			});
			newChatMsgKeys.forEach(val => {
				const newChatMsgs = uni.getStorageSync(val) || [];
				if (newChatMsgs.length) {
					lastChatMsg = this.returnChatMsg(newChatMsgs);
					console.log(lastChatMsg);
					lastChatMsg.unReadCount = this.unReadCount(newChatMsgs);
					array.push(lastChatMsg);
				}
			});
			array.sort((a, b) => b.dateTimeNum - a.dateTimeNum);
			array.sort((a, b) => (a.isTop ? -1 : 1));
			const signChatArr = [];
			this.dataList = array
				.map((val, i) => {
					const txt = Array.isArray(val.msg.data) && val.msg.data.length > 0 ? val.msg.data[0].data : '';
					const msg = {
						image: '[图片消息]',
						img: '[图片消息]',
						location: '[位置消息]',
						audio: '[暂不支持此类消息]',
						video: '[暂不支持此类消息]',
						custom: '[邀请消息]',
						system_tips: '[系统消息]',
						txt
					}[val.msg.type];
					val.data = msg;
					val.show = false;
					const item = this.listGroup.find(item => item.groupid === val.info.to);
					if (item) {
						val.groupname = item.groupname;
						val.chatName = item.chatName || item.groupname;
						val.avatar = item.avatar;
						val.username = item.groupid;
						return val;
					}
					if (val.username === 'gbwadmin') {
						this.$set(val, 'chatName', '剧烈运动官方');
						this.$set(val, 'avatar', '/wx/julie_logo.png');
					}
					const toLen = val.info.to; //发送到哪个id
					if (!item && toLen.indexOf('gbwlarp') === -1) {
						//删除当前本地聊天历史记录
						const key = `${val.username}${this.$store.getters.loginForm.hxUsername}`;
						const historyChatMsgKeys = `rendered_${key}`;
						uni.removeStorageSync(historyChatMsgKeys);
						uni.removeStorageSync(key);
					}
					if (toLen.indexOf('gbwlarp') > -1) {
						signChatArr.push(val); //储存私聊类型 环信用户id包含gbwlarp
						return val;
					}
				})
				.filter(val => val); //本地消息
			const ids = signChatArr.map(val => val.username);
			if (!ids.length) return false;
			add(
				{
					singleData: ids,
					showLoading: true,
					type: 'single' //不是对象
				},
				'user',
				'shopApi',
				'findChatDtoByHxUsernames'
			).then(res => {
				res.forEach(val => {
					const item = this.dataList.find(c => c.username === val.hxUsername);
					if (item) {
						this.$set(item, 'chatName', val.nickname);
						this.$set(item, 'avatar', val.avatar);
					}
				});
			});
			disp.fire('em.chat.readyNum');
			//this.dataList = [...this.dataList,...groupList]
		},
		unReadCount(newChatMsgs) {
			return Array.isArray(newChatMsgs) && newChatMsgs.filter(val => val.style !== 'self').length;
		},
		goPath(index) {
			const item = this.dataList[index];
			const chatName = item.chatName;
			const id = item.username;
			this.__visibility__ = false;
			this.$u.route({
				url: '/pages/chat/chat',
				params: {
					type: item.groupname ? 'groupChat' : 'singleChat',
					name: chatName,
					id
				}
			});
		}
	},
	filters: {
		filterTime(val) {
			if (!val) return '';
			return formatTime(val);
		}
	}
};
</script>

<style lang="scss" scpoed>
.text-last-msg {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: calc(100vw - 400rpx);
	min-height: 28rpx;
}
.time {
	right: 20rpx;
	top: 0rpx;
}
</style>
